<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header class="header-container">
        <div class="headerTitle">查询条件</div>
        <div class="header-content">
          <el-form :model="headerSearchForm" label-width="auto" class="header-search-form">
            <el-form-item label="任务名称">
              <el-input v-model="headerSearchForm.productionLine" placeholder="请输入任务名称" style="width:170px" />
            </el-form-item>
            <el-form-item label="提交人">
              <el-input v-model="headerSearchForm.variableName" placeholder="请输入提交人" style="width:120px" />
            </el-form-item>
            <el-form-item label="开始时间" style="margin-left:20px">
              <el-date-picker v-model="headerSearchForm.start" type="datetime" class="w-15vw" placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" style="margin-left:20px">
              <el-date-picker v-model="headerSearchForm.end" type="datetime" class="w-15vw " placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>



          </el-form>
          <div class="header-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="primary" @click="handleReset">重置</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="table-container-main">
          <el-table :data="tableData" :cell-class-name="bandCellClassName"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            :row-class-name="tableRowClassName">
            <el-table-column prop="serialNumber" label="序号" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="areaCode" label="任务名称" width="120"/>
            <el-table-column prop="deviceCode" label="钢种" />
            <el-table-column prop="exWidth" label="宽度" />
            <el-table-column prop="enThick" label="入口厚度" width="90"/>
            <el-table-column prop="exThick" label="出口厚度" width="90"/>
            <!-- 改为与 acidrollingproduct.vue 一致的 S1~S5 分列显示 -->
            <el-table-column label="轧制力(kN)" header-align="center">
              <el-table-column prop="RollForceS1" label="S1" width="85px" />
              <el-table-column prop="RollForceS2" label="S2" width="85px" />
              <el-table-column prop="RollForceS3" label="S3" width="85px" />
              <el-table-column prop="RollForceS4" label="S4" width="85px" />
              <el-table-column prop="RollForceS5" label="S5" width="85px" />
            </el-table-column>
            <el-table-column label="厚度(mm)" header-align="center">
              <el-table-column prop="ThickS1" label="S1" width="85px" />
              <el-table-column prop="ThickS2" label="S2" width="85px" />
              <el-table-column prop="ThickS3" label="S3" width="85px" />
              <el-table-column prop="ThickS4" label="S4" width="85px" />
              <el-table-column prop="ThickS5" label="S5" width="85px" />
            </el-table-column>
            <el-table-column label="速度(m/min)" header-align="center">
              <el-table-column prop="SpeedS1" label="S1" width="85px" />
              <el-table-column prop="SpeedS2" label="S2" width="85px" />
              <el-table-column prop="SpeedS3" label="S3" width="85px" />
              <el-table-column prop="SpeedS4" label="S4" width="85px" />
              <el-table-column prop="SpeedS5" label="S5" width="85px" />
            </el-table-column>
            <el-table-column label="辊缝(mm)" header-align="center">
              <el-table-column prop="GapS1" label="S1" width="85px" />
              <el-table-column prop="GapS2" label="S2" width="85px" />
              <el-table-column prop="GapS3" label="S3" width="85px" />
              <el-table-column prop="GapS4" label="S4" width="85px" />
              <el-table-column prop="GapS5" label="S5" width="85px" />
            </el-table-column>
            <el-table-column label="张力(kN)" header-align="center">
              <el-table-column prop="ZHS6" label="机架前" width="85px" />
              <el-table-column prop="ZHS1" label="S1" width="85px" />
              <el-table-column prop="ZHS2" label="S2" width="85px" />
              <el-table-column prop="ZHS3" label="S3" width="85px" />
              <el-table-column prop="ZHS4" label="S4" width="85px" />
              <el-table-column prop="ZHS5" label="S5" width="85px" />
            </el-table-column>
            
            <el-table-column label="功率(kW)" header-align="center">
              <el-table-column prop="PowerS1" label="S1" width="85px" />
              <el-table-column prop="PowerS2" label="S2" width="85px" />
              <el-table-column prop="PowerS3" label="S3" width="85px" />
              <el-table-column prop="PowerS4" label="S4" width="85px" />
              <el-table-column prop="PowerS5" label="S5" width="85px" />
            </el-table-column>
            <!-- <el-table-column prop="variableName" label="仿真类型" /> -->
            <el-table-column prop="variableDescription" label="提交人" width="120"/>
            <el-table-column prop="dataSource" label="备注" width="120"/>
            <el-table-column prop="triggerMark" label="时间" width="180"/>
            <el-table-column label="操作" fixed="right" width="240">
              <template #default="scope">
                <template v-if="scope.row.status === 2">
                  <span class="dot-loading" style="font-size: 13px;">· · ·计算中</span>
                </template>
                <template v-else>
                  <el-button type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.status !== 1" :class="{'btn-disabled': scope.row.status === 0}">删除</el-button>
                  <el-button type="warning" @click="handleCheck(scope.row)" :disabled="scope.row.status !== 1" :class="{'btn-disabled': scope.row.status === 0}">查看</el-button>
                  <el-button type="primary" @click="handleQuote(scope.row)" :disabled="scope.row.status !== 1" :class="{'btn-disabled': scope.row.status === 0}">引用</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-main>
    </el-container>
    <el-dialog v-model="dialogVisible" title="轧制规程仿真"
      style="text-align: left;width: 80%;--el-dialog-title-font-size: 16px;">
      <el-row>
        <el-col style="font-size:12px">
          <div class="msg-title">PDI信息输入</div>
        </el-col>
      </el-row>
      <el-row style="margin-top:10px;margin-left:15px">
        <el-col :span="3" style="font-size:12px">
          <div>
            <span>产品牌号</span>
            <el-input v-model="dialogPdiData.COILNO" placeholder="请输入产品编号"
              style="width:80px;height:20px;margin-left:4px;" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>屈服强度</span>
            <el-input v-model="dialogPdiData.YP" placeholder="请输入产品编号" style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>入口厚度</span>
            <el-input v-model="dialogPdiData.EN_THICK" placeholder="请输入产品编号"
              style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>入口宽度</span>
            <el-input v-model="dialogPdiData.EN_WIDTH" placeholder="请输入产品编号"
              style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>成品厚度</span>
            <el-input v-model="dialogPdiData.EX_THICK" placeholder="请输入产品编号"
              style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>成品宽度</span>
            <el-input v-model="dialogPdiData.EX_WIDTH" placeholder="请输入产品编号"
              style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
        </el-col>
      </el-row>
      <el-row style="margin-top:10px;margin-left:15px">
        <el-col :span="5" style="font-size:12px;">
          <div>
            <span>任务名称</span>
            <el-input v-model="dialogPdiData.taskName" placeholder="请输入产品编号"
              style="width:160px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="5" style="font-size:12px;margin-left:10px">
          <div>
            <span>提交人</span>
            <el-input v-model="dialogPdiData.submitter" placeholder="请输入产品编号"
              style="width:160px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="5" style="font-size:12px;">
          <div>
            <span>备注</span>
            <el-input v-model="dialogPdiData.remarkText" placeholder="请输入产品编号"
              style="width:180px;height:20px;margin-left:4px" />
          </div>
        </el-col>


      </el-row>
      
      <el-row>
        <el-col style="font-size:12px">
          <div class="msg-title">轧制规程参数</div>
        </el-col>
      </el-row>

      <el-row style="margin-top:10px;margin-left:15px;display:flex">
        <el-col style="font-size:12px;" :span="18">
          <el-table :data="dialogScheduleTableData" style="width: 100%"
            :header-cell-style="{ background: '#2f59af', color: '#fff', fontSize: '12px' }"
            :cell-style="{ fontSize: '12px' }">
            <el-table-column prop="TITLE" label="轧制规程参数" width="180" />
            <el-table-column prop="S5" label="S5" />
            <el-table-column prop="S4" label="S4" />
            <el-table-column prop="S3" label="S3" />
            <el-table-column prop="S2" label="S2" />
            <el-table-column prop="S1" label="S1" />
            <el-table-column prop="BEFORE" label="机架前" />
          </el-table>
        </el-col>
        <el-col :span="5">
          <nercar-echarts :graphic="echartsListOptions[0].graphic" :title="echartsListOptions[0].title"
            :grid="echartsListOptions[0].grid" :x-axis="echartsListOptions[0].xAxis"
            :y-axis="echartsListOptions[0].yAxis" :tooltip="echartsListOptions[0].tooltip"
            :series="echartsListOptions[0].series" style="width:260px;height:190px !important;" />

        </el-col>
      </el-row>
      <el-row style="margin-top:1px;margin-left:15px;margin-bottom: 10px;">
        <el-col :span="3" style="font-size:12px">
          <div>
            <span>L</span>
            <el-input v-model="dialogPdiData.L_value" placeholder="L值"
              style="width:80px;height:20px;margin-left:4px;" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>M</span>
            <el-input v-model="dialogPdiData.M_value" placeholder="M值" style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
        <el-col :span="3" style="font-size:12px;margin-left:10px">
          <div>
            <span>N</span>
            <el-input v-model="dialogPdiData.N_value" placeholder="N值" style="width:80px;height:20px;margin-left:4px" />
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col style="font-size:12px">
          <div class="msg-title">仿真计算结果输出</div>
        </el-col>
      </el-row>
      <el-row style="margin-top:10px;margin-left:15px">
        <el-col style="font-size:12px;">
          <el-table :data="dialogSimulationOutputTableData" style="width: 100%"
            :header-cell-style="{ background: '#2f59af', color: '#fff', fontSize: '12px' }"
            :cell-style="{ fontSize: '12px' }">
            <el-table-column prop="TITLE" label="计算结果" width="180" />
            <el-table-column prop="S5" label="S5" />
            <el-table-column prop="S4" label="S4" />
            <el-table-column prop="S3" label="S3" />
            <el-table-column prop="S2" label="S2" />
            <el-table-column prop="S1" label="S1" />
            <el-table-column prop="BEFORE" label="机架前" />
          </el-table>
        </el-col>
      </el-row>


    </el-dialog>


  </div>
</template>
<script lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, defineComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import '/@/views/RollingSimulation/rollingSimulationModelCommonStyle.less';
import NercarEcharts from '/@/components/NercarEcharts/NercarEcharts.vue'
import { rollingSimulationApi } from '/@/api/RollingSimulation/index';
import { processParamApi } from '/@/api/report/index';

// Interface for Search Form - Keep existing or adjust if needed
interface SearchForm {
  productionLine: string; // Mapped to API's volumeNum (Task Name)
  variableDescription: string; // Progress - Not used by API
  variableName: string; // Mapped to API's operator (Submitter)
  start: string | Date; // Start Time
  end: string | Date;   // End Time
}

// (removed unused ApiMappings interface)

// Interface for API request parameters
interface FindCaseDataParams {
  volumeNum?: string;
  operator?: string;
  startDate?: string;
  endDate?: string;
  pageIndex: string;
  pageSize: string;
}

// Interface for API response data item
interface CaseDataRecord {
  coilNo: string;
  steelGrade: string;
  operator: string;
  remark: string;
  recCreateTime: string;
  status?: number; // 0未计算 1已计算 2计算中
  areaCode?: string;
  deviceCode?: string;
  exWidth?: string;
  enThick?: string;
  exThick?: string;
  variableDescription?: string;
  dataSource?: string;
  // 可选：列表若直接返回S1~S5数据，用于在表格展示（与弹窗字段一致）
  thk1?: number; thk2?: number; thk3?: number; thk4?: number; thk5?: number;
  speed1?: number; speed2?: number; speed3?: number; speed4?: number; speed5?: number;
  gap1?: number; gap2?: number; gap3?: number; gap4?: number; gap5?: number;
  tension1?: number; tension2?: number; tension3?: number; tension4?: number; tension5?: number; tension6?: number;
  rollForce1?: number; rollForce2?: number; rollForce3?: number; rollForce4?: number; rollForce5?: number;
  power1?: number; power2?: number; power3?: number; power4?: number; power5?: number;
}

// Interface for PDI data displayed in the dialog's header section
// Ensure your dialog's template v-models bind to these exact field names
interface CaseViewPdiData {
  taskName?: string | number;      // Populated from main table row.areaCode (which is coilNo)
  submitter?: string | number;     // Populated from API details.operator
  remarkText?: string | number;    // Populated from API details.remark

  COILNO?: string | number;        // For '产品牌号' display, from API details.steelGrade
  YP?: string | number;            // For '屈服强度' display, from API details.yp
  EN_THICK?: string | number;    // For '入口厚度' display, from API details.enThick
  EX_THICK?: string | number;    // For '成品厚度' display, from API details.exThick
  EN_WIDTH?: string | number;    // For '入口宽度' display, from API details.enWidth
  EX_WIDTH?: string | number;    // For '成品宽度' display, from API details.exWidth

  L_value?: string | number;       // For 'L' value display, from API details.l
  M_value?: string | number;       // For 'M' value display, from API details.m
  N_value?: string | number;       // For 'N' value display, from API details.n
}

// Interface for the full data from findCase API (this should match API's camelCase structure)
interface CaseFullDetails {
  // PDI Info - direct from API (camelCase)
  coilNo?: string;
  steelGrade?: string; // API might also return steelGrade with details
  yp?: number;
  enThick?: number;
  exThick?: number;
  enWidth?: number;
  exWidth?: number;
  operator?: string; // Raw operator field from API
  remark?: string;   // Raw remark field from API
  l?: number;        // L value from API
  m?: number;        // M value from API
  n?: number;        // N value from API

  // Schedule parameters - camelCase from API
  thk1?: number; thk2?: number; thk3?: number; thk4?: number; thk5?: number;
  speed1?: number; speed2?: number; speed3?: number; speed4?: number; speed5?: number; speed6?: number;
  tension1?: number; tension2?: number; tension3?: number; tension4?: number; tension5?: number; tension6?: number;
  rollForce1?: number; rollForce2?: number; rollForce3?: number; rollForce4?: number; rollForce5?: number;
  rollingForeceSet1?: number; rollingForeceSet2?: number; rollingForeceSet3?: number; rollingForeceSet4?: number; rollingForeceSet5?: number;
  rollingForceSet1?: number; rollingForceSet2?: number; rollingForceSet3?: number; rollingForceSet4?: number; rollingForceSet5?: number;
  wrDia1?: number; wrDia2?: number; wrDia3?: number; wrDia4?: number; wrDia5?: number;
  nr1?: number; nr2?: number; nr3?: number; nr4?: number; nr5?: number;
  wrBend1?: number; wrBend2?: number; wrBend3?: number; wrBend4?: number; wrBend5?: number;
  mrBend1?: number; mrBend2?: number; mrBend3?: number; mrBend4?: number; mrBend5?: number;
  power1?: number; power2?: number; power3?: number; power4?: number; power5?: number;
  deformRate1?: number; deformRate2?: number; deformRate3?: number; deformRate4?: number; deformRate5?: number;
  unitTension1?: number; unitTension2?: number; unitTension3?: number; unitTension4?: number; unitTension5?: number; unitTension6?: number;
  gap1?: number;
  gap2?: number;
  gap3?: number;
  gap4?: number;
  gap5?: number;
  forslip1?: number;
  forslip2?: number;
  forslip3?: number;
  forslip4?: number;
  forslip5?: number;
  
  // 新增：变形抗力曲线图数据
  rfNewV?: string;   // RF_NEW_V数据，作为x轴
  ksv?: string;      // KS_V数据，作为y轴
  
  // 新增：最终压下率字段
  redsFinal1?: number;
  redsFinal2?: number;
  redsFinal3?: number;
  redsFinal4?: number;
  redsFinal5?: number;
}

// (removed several unused interface declarations)

export default defineComponent({
  name: 'DataDictionary',
  setup() {
    const router = useRouter();
    
    const handleQuote = (row: CaseDataRecord) => {
      if (!row.areaCode) {
        ElMessage.error('无法获取案例的任务名称 (areaCode)');
        return;
      }
      router.push({
        path: '/rollingsimulation/rollingsimulationl',
        query: {
          taskName: row.areaCode
        }
      });
    };
    const headerSearchForm = reactive<SearchForm>({
      productionLine: '',
      variableDescription: '',
      variableName: '',
      start: '',
      end: ''
    });
    const dialogVisible = ref<boolean>(false);
    const dialogPdiData = reactive<CaseViewPdiData>({});
    const dialogScheduleTableData = ref<any[]>([]);
    const dialogSimulationOutputTableData = ref<any[]>([]);
    const tableData = ref<CaseDataRecord[]>([]);
    const dataSourceType = ref('');
    const dataSourceTypeOptions = ref([
      { label: 'PLC', value: 'PLC' },
      { label: '传感器', value: '传感器' },
      { label: 'AI算法', value: 'AI算法' },
      { label: '称重传感器', value: '称重传感器' },
      { label: '电池管理系统', value: '电池管理系统' },
    ]);

    const footTable = ref([ // This is a fallback or placeholder if needed, dialog uses dynamic data
      { '卷号': '工作辊直径(mm)', '钢种': '-', '宽度': '430', '厚度': '440', '命中率': '450' },
      { '卷号': '单位张力(MPa)', '钢种': '40', '宽度': '97.4', '厚度': '121', '命中率': '134.8' },
      { '卷号': '比变形率', '钢种': '-', '宽度': '32', '厚度': '30', '命中率': '26' },
      { '卷号': '轧制卷数', '钢种': '-', '宽度': '100', '厚度': '100', '命中率': '100' },
      { '卷号': '支撑辊辊径(mm)', '钢种': '-', '宽度': '1300', '厚度': '1300', '命中率': '1300' },
    ]);

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    const handleResize = () => {
      nextTick(() => {
      });
    };
    // 纵向分组：从“轧制力(kN)”开始到“功率(kW)”结束的所有一级组交替浅蓝，其余不着色
    function bandCellClassName({ column }: { column: any }) {
      const prop: string = column?.property || '';
      // 一级组前缀（包含其 S1~S5 子列的字段前缀）
      const groupPrefixes = [
        'RollForceS', // 轧制力
        'ThickS',     // 厚度
        'SpeedS',     // 速度
        'GapS',       // 辊缝
        'ZHS',        // 张力
        'PowerS'      // 功率
      ];
      const idx = groupPrefixes.findIndex(prefix => prop.startsWith(prefix));
      if (idx === -1) return '';
      // 只对范围内(轧制力..功率)的组进行交替涂色：偶数组高亮
      return idx % 2 === 0 ? 'band-blue' : '';
    }

    // 调用 techList 和 techFit 接口
    const callTechListAndTechFit = async () => {
      try {
        // 准备参数，按照你提供的参数结构
        const techListParams = {
          startDate: '',
          endDate: '',
          prodLine: '',
          steelGrade: '',
          thickStart: 0,
          thickEnd: 0,
          entWidthStart: 0,
          entWidthEnd: 0,
          levelStart: 0,
          levelEnd: 0,
          contrTarget: 0,
          param: ''
        };

        const techFitParams = {
          startDate: '',
          endDate: '',
          prodLine: '',
          steelGrade: '',
          thickStart: 0,
          thickEnd: 0,
          entWidthStart: 0,
          entWidthEnd: 0,
          levelStart: 0,
          levelEnd: 0,
          contrTarget: 0,
          param: ''
        };

        console.log('调用 techList 接口，参数:', techListParams);
        const techListResponse = await processParamApi.techList(techListParams);
        console.log('techList 接口返回结果:', techListResponse);

        console.log('调用 techFit 接口，参数:', techFitParams);
        const techFitResponse = await processParamApi.techFit(techFitParams);
        console.log('techFit 接口返回结果:', techFitResponse);

      } catch (error) {
        console.error('调用 techList 或 techFit 接口失败:', error);
      }
    };

    // Definition for displayValue function
    const displayValue = (val: any): string | number => {
      if (val === null || val === undefined || String(val).trim() === '') {
        return '-';
      }
      if (typeof val === 'number' && val === 0) {
        return 0;
      }
      return val;
    };

    // =============== 列表 S1~S5 展示格式化 ===============
    const joinS1toS5 = (arr: (number | string | undefined)[], unit?: string, fixed?: number) => {
      const fmt = (v: any) => {
        if (v === null || v === undefined || v === '') return '-';
        const num = Number(v);
        if (Number.isFinite(num)) return fixed !== undefined ? num.toFixed(fixed) : String(num);
        return String(v);
      };
      const result = arr.map(fmt).join(' / ');
      return unit ? `${result}${unit ? '' : ''}` : result;
    };

    const formatThicknessS1toS5 = (row: Partial<CaseDataRecord>) => {
      return joinS1toS5([row.thk1, row.thk2, row.thk3, row.thk4, row.thk5], undefined, 3);
    };
    const formatSpeedS1toS5 = (row: Partial<CaseDataRecord>) => {
      return joinS1toS5([row.speed1, row.speed2, row.speed3, row.speed4, row.speed5]);
    };
    const formatGapS1toS5 = (row: Partial<CaseDataRecord>) => {
      return joinS1toS5([row.gap1, row.gap2, row.gap3, row.gap4, row.gap5], undefined, 3);
    };
    const formatTensionS1toS5 = (row: Partial<CaseDataRecord>) => {
      // 与弹窗一致：kN 显示时列表同样乘以10并保留3位小数
      const mul10 = (v?: number) => (v !== undefined ? Number(v) * 10 : undefined);
      return joinS1toS5([mul10(row.tension1), mul10(row.tension2), mul10(row.tension3), mul10(row.tension4), mul10(row.tension5)], undefined, 3);
    };
    const formatRollForceS1toS5 = (row: Partial<CaseDataRecord>) => {
      const mul10 = (v?: number) => (v !== undefined ? Number(v) * 10 : undefined);
      return joinS1toS5([mul10(row.rollForce1), mul10(row.rollForce2), mul10(row.rollForce3), mul10(row.rollForce4), mul10(row.rollForce5)], undefined, 3);
    };
    const formatPowerS1toS5 = (row: Partial<CaseDataRecord>) => {
      return joinS1toS5([row.power1, row.power2, row.power3, row.power4, row.power5]);
    };

    const transformApiDataToScheduleTable = (apiData: CaseFullDetails) => [
      { TITLE: '工作辊直径(mm)', BEFORE: '-', S1: apiData.wrDia1 !== undefined ? String(Math.round(Number(apiData.wrDia1))) : '-', S2: apiData.wrDia2 !== undefined ? String(Math.round(Number(apiData.wrDia2))) : '-', S3: apiData.wrDia3 !== undefined ? String(Math.round(Number(apiData.wrDia3))) : '-', S4: apiData.wrDia4 !== undefined ? String(Math.round(Number(apiData.wrDia4))) : '-', S5: apiData.wrDia5 !== undefined ? String(Math.round(Number(apiData.wrDia5))) : '-' },
      { TITLE: '轧制卷数', BEFORE: '-', S1: apiData.nr1 ?? '-', S2: apiData.nr2 ?? '-', S3: apiData.nr3 ?? '-', S4: apiData.nr4 ?? '-', S5: apiData.nr5 ?? '-' },
      { TITLE: '比变形率', BEFORE: '-', S1: apiData.deformRate1 ?? '-', S2: apiData.deformRate2 ?? '-', S3: apiData.deformRate3 ?? '-', S4: apiData.deformRate4 ?? '-', S5: apiData.deformRate5 ?? '-' },
      { TITLE: '单位张力(MPa)', BEFORE: apiData.unitTension1 ?? '-', S1: apiData.unitTension2 ?? '-', S2: apiData.unitTension3 ?? '-', S3: apiData.unitTension4 ?? '-', S4: apiData.unitTension5 ?? '-' ,S5: apiData.unitTension6 ?? '-' }
    ];

    const transformApiDataToSimulationOutputTable = (apiData: CaseFullDetails) => [
      { TITLE: '出口厚度(mm)', BEFORE: '-', S1: apiData.thk1 !== undefined ? Number(apiData.thk1).toFixed(3) : '-', S2: apiData.thk2 !== undefined ? Number(apiData.thk2).toFixed(3) : '-', S3: apiData.thk3 !== undefined ? Number(apiData.thk3).toFixed(3) : '-', S4: apiData.thk4 !== undefined ? Number(apiData.thk4).toFixed(3) : '-', S5: apiData.thk5 !== undefined ? Number(apiData.thk5).toFixed(3) : '-' },
      { TITLE: '机架速度(mpm)', BEFORE: '-', S1: apiData.speed1 ?? '-', S2: apiData.speed2 ?? '-', S3: apiData.speed3 ?? '-', S4: apiData.speed4 ?? '-', S5: apiData.speed5 ?? '-' },
      { TITLE: '张力(kN)', BEFORE: apiData.tension6 !== undefined ? (apiData.tension6 * 10).toFixed(3) : '-', S1: apiData.tension1 !== undefined ? (apiData.tension1 * 10).toFixed(3) : '-', S2: apiData.tension2 !== undefined ? (apiData.tension2 * 10).toFixed(3) : '-', S3: apiData.tension3 !== undefined ? (apiData.tension3 * 10).toFixed(3) : '-', S4: apiData.tension4 !== undefined ? (apiData.tension4 * 10).toFixed(3) : '-', S5: apiData.tension5 !== undefined ? (apiData.tension5 * 10).toFixed(3) : '-' },
      { TITLE: '轧制力(kN)', BEFORE: '-', S1: apiData.rollForce1 !== undefined ? (apiData.rollForce1 * 10).toFixed(3) : '-', S2: apiData.rollForce2 !== undefined ? (apiData.rollForce2 * 10).toFixed(3) : '-', S3: apiData.rollForce3 !== undefined ? (apiData.rollForce3 * 10).toFixed(3) : '-', S4: apiData.rollForce4 !== undefined ? (apiData.rollForce4 * 10).toFixed(3) : '-', S5: apiData.rollForce5 !== undefined ? (apiData.rollForce5 * 10).toFixed(3) : '-' },
      { TITLE: '电机功率(kW)', BEFORE: '-', S1: apiData.power1 ?? '-', S2: apiData.power2 ?? '-', S3: apiData.power3 ?? '-', S4: apiData.power4 ?? '-', S5: apiData.power5 ?? '-' },
      { TITLE: '辊缝(mm)', BEFORE: '-', S1: apiData.gap1 !== undefined ? Number(apiData.gap1).toFixed(3) : '-', S2: apiData.gap2 !== undefined ? Number(apiData.gap2).toFixed(3) : '-', S3: apiData.gap3 !== undefined ? Number(apiData.gap3).toFixed(3) : '-', S4: apiData.gap4 !== undefined ? Number(apiData.gap4).toFixed(3) : '-', S5: apiData.gap5 !== undefined ? Number(apiData.gap5).toFixed(3) : '-' },
      { TITLE: '前滑值(%)', BEFORE: '-', S1: apiData.forslip1 !== undefined ? (Number(apiData.forslip1) * 100).toFixed(2) + '%' : '-', S2: apiData.forslip2 !== undefined ? (Number(apiData.forslip2) * 100).toFixed(2) + '%' : '-', S3: apiData.forslip3 !== undefined ? (Number(apiData.forslip3) * 100).toFixed(2) + '%' : '-', S4: apiData.forslip4 !== undefined ? (Number(apiData.forslip4) * 100).toFixed(2) + '%' : '-', S5: apiData.forslip5 !== undefined ? (Number(apiData.forslip5) * 100).toFixed(2) + '%' : '-' },
      { TITLE: '最终压下率(%)', BEFORE: '-', S1: apiData.redsFinal1 !== undefined ? (Number(apiData.redsFinal1) * 100).toFixed(2) + '%' : '-', S2: apiData.redsFinal2 !== undefined ? (Number(apiData.redsFinal2) * 100).toFixed(2) + '%' : '-', S3: apiData.redsFinal3 !== undefined ? (Number(apiData.redsFinal3) * 100).toFixed(2) + '%' : '-', S4: apiData.redsFinal4 !== undefined ? (Number(apiData.redsFinal4) * 100).toFixed(2) + '%' : '-', S5: apiData.redsFinal5 !== undefined ? (Number(apiData.redsFinal5) * 100).toFixed(2) + '%' : '-' }
    ];

    const handleCheck = async (row: CaseDataRecord) => {
      if (!row.coilNo) {
        ElMessage.error('无法获取案例的唯一标识 (coilNo)');
        return;
      }
      try {
        Object.keys(dialogPdiData).forEach(key => delete dialogPdiData[key as keyof CaseViewPdiData]);
        dialogScheduleTableData.value = [];
        dialogSimulationOutputTableData.value = [];

        const response = await rollingSimulationApi.findCase({ volumeNum: row.coilNo });

        // Try to access details from response.data.data.data first, then fallback to response.data.data
        let details: CaseFullDetails | null = null;
        if (response && response.data && response.data.data && typeof response.data.data === 'object' && !Array.isArray(response.data.data.data) && response.data.data.data) {
          console.log('Accessing details from response.data.data.data');
          details = response.data.data.data as CaseFullDetails;
        } else if (response && response.data && typeof response.data.data === 'object' && !Array.isArray(response.data.data)) {
          console.log('Accessing details from response.data.data (fallback)');
          details = response.data.data as CaseFullDetails;
        } else if (response && response.data && typeof response.data === 'object') {
          // This case would match if the primary data object is directly under response.data
          // (as per the sample JSON you provided for the API response itself)
          console.log('Accessing details directly from response.data (if it matches CaseFullDetails structure)');
          details = response.data as CaseFullDetails;
        }

        if (details) {
          // Populate dialogPdiData - ensure these field names match your dialog template v-models
          dialogPdiData.taskName = displayValue(row.areaCode);
          dialogPdiData.submitter = details.operator;
          dialogPdiData.remarkText = row.dataSource;

          dialogPdiData.COILNO = details.steelGrade;
          dialogPdiData.YP = details.yp;
          dialogPdiData.EN_THICK = details.enThick;
          dialogPdiData.EX_THICK = details.exThick;
          dialogPdiData.EN_WIDTH = details.enWidth;
          dialogPdiData.EX_WIDTH = details.exWidth;

          dialogPdiData.L_value = details.l;
          dialogPdiData.M_value = details.m;
          dialogPdiData.N_value = details.n;

          dialogScheduleTableData.value = transformApiDataToScheduleTable(details);
          dialogSimulationOutputTableData.value = transformApiDataToSimulationOutputTable(details);

          // 新增：渲染变形抗力曲线图（rfNewV为x轴，ksv为y轴）
          if (details.rfNewV && details.ksv) {
            const ksvArr = String(details.ksv).split(',').map(v => v.trim()).filter(v => v !== '').map(Number);
            let rfNewVArr = String(details.rfNewV).split(',').map(v => v.trim()).filter(v => v !== '').map(Number);
            
            // 横坐标等距平均分布并乘以100
            if (rfNewVArr.length > 1) {
              const min = Math.min(...rfNewVArr);
              const max = Math.max(...rfNewVArr);
              const step = (max - min) / (rfNewVArr.length - 1);
              rfNewVArr = Array.from({ length: rfNewVArr.length }, (_, i) => ((min + i * step) * 100));
            } else if (rfNewVArr.length === 1) {
              rfNewVArr = [rfNewVArr[0] * 100];
            }
            
            // 转为字符串数组，去掉小数位
            const rfNewVArrStr = rfNewVArr.map(v => Math.round(v).toString());
            if (Array.isArray(ksvArr) && Array.isArray(rfNewVArrStr) && ksvArr.length === rfNewVArrStr.length && ksvArr.length > 0) {
              echartsListOptions[0].series[0].data = ksvArr;
              echartsListOptions[0].xAxis[0].data = rfNewVArrStr;
            }
          }

          console.log('Dialog PDI Data:', JSON.parse(JSON.stringify(dialogPdiData)));
          console.log('Dialog Schedule Table Data:', JSON.parse(JSON.stringify(dialogScheduleTableData.value)));
          console.log('Dialog Simulation Output Table Data:', JSON.parse(JSON.stringify(dialogSimulationOutputTableData.value)));

          dialogVisible.value = true;
        } else {
          ElMessage.error(response?.data?.msg || '查询案例详情失败或数据结构不正确');
        }
      } catch (error: any) {
        console.error('查询案例详情失败:', error);
        ElMessage.error(error.response?.data?.msg || error.message || '查询案例详情失败');
      }
    };

    const fetchTableData = async () => {
      try {
        const formatDate = (date: string | Date | null | undefined): string | undefined => {
          if (!date) return undefined;
          if (date instanceof Date) {
            const pad = (num: number) => num.toString().padStart(2, '0');
            return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
          }
          return date;
        };

        const params: FindCaseDataParams = {
          volumeNum: headerSearchForm.productionLine || undefined,
          operator: headerSearchForm.variableName || undefined,
          startDate: formatDate(headerSearchForm.start),
          endDate: formatDate(headerSearchForm.end),
          pageIndex: String(pagination.currentPage),
          pageSize: String(pagination.pageSize),
        };

        Object.keys(params).forEach(key => {
          if (params[key as keyof FindCaseDataParams] === undefined) {
            delete params[key as keyof FindCaseDataParams];
          }
        });

        const response = await rollingSimulationApi.findCaseData(params);

        if (response && response.data && Array.isArray(response.data.data)) {
          const responsePayload = response.data;
          const records = responsePayload.data;

          const mappedData = records.map((record: CaseDataRecord) => {
            // 兼容API无status字段时补0
            const status = typeof record.status === 'number' ? record.status : 0;
            return {
            areaCode: record.coilNo ?? '-',
            deviceCode: record.steelGrade ?? '-',
            variableName: '轧制规格仿真',
            variableAlias: '0',
            variableDescription: record.operator ?? '-',
            dataSource: record.remark ?? '-',
            triggerMark: record.recCreateTime ? new Date(record.recCreateTime).toLocaleString() : '-',
              // S1~S5 分列（与弹窗保持一致的处理规则）
              ThickS1: record.thk1 !== undefined ? Number(record.thk1).toFixed(3) : '-',
              ThickS2: record.thk2 !== undefined ? Number(record.thk2).toFixed(3) : '-',
              ThickS3: record.thk3 !== undefined ? Number(record.thk3).toFixed(3) : '-',
              ThickS4: record.thk4 !== undefined ? Number(record.thk4).toFixed(3) : '-',
              ThickS5: record.thk5 !== undefined ? Number(record.thk5).toFixed(3) : '-',

              SpeedS1: typeof record.speed1 === 'number' ? Math.round(record.speed1) : '-',
              SpeedS2: typeof record.speed2 === 'number' ? Math.round(record.speed2) : '-',
              SpeedS3: typeof record.speed3 === 'number' ? Math.round(record.speed3) : '-',
              SpeedS4: typeof record.speed4 === 'number' ? Math.round(record.speed4) : '-',
              SpeedS5: typeof record.speed5 === 'number' ? Math.round(record.speed5) : '-',

              GapS1: record.gap1 !== undefined ? Number(record.gap1).toFixed(3) : '-',
              GapS2: record.gap2 !== undefined ? Number(record.gap2).toFixed(3) : '-',
              GapS3: record.gap3 !== undefined ? Number(record.gap3).toFixed(3) : '-',
              GapS4: record.gap4 !== undefined ? Number(record.gap4).toFixed(3) : '-',
              GapS5: record.gap5 !== undefined ? Number(record.gap5).toFixed(3) : '-',

              ZHS1: typeof record.tension1 === 'number' ? Math.round(record.tension1 * 10) : '-',
              ZHS2: typeof record.tension2 === 'number' ? Math.round(record.tension2 * 10) : '-',
              ZHS3: typeof record.tension3 === 'number' ? Math.round(record.tension3 * 10) : '-',
              ZHS4: typeof record.tension4 === 'number' ? Math.round(record.tension4 * 10) : '-',
              ZHS5: typeof record.tension5 === 'number' ? Math.round(record.tension5 * 10) : '-',
              ZHS6: typeof record.tension6 === 'number' ? Math.round(record.tension6 * 10) : '-',

              RollForceS1: typeof record.rollForce1 === 'number' ? Math.round(record.rollForce1 * 10) : '-',
              RollForceS2: typeof record.rollForce2 === 'number' ? Math.round(record.rollForce2 * 10) : '-',
              RollForceS3: typeof record.rollForce3 === 'number' ? Math.round(record.rollForce3 * 10) : '-',
              RollForceS4: typeof record.rollForce4 === 'number' ? Math.round(record.rollForce4 * 10) : '-',
              RollForceS5: typeof record.rollForce5 === 'number' ? Math.round(record.rollForce5 * 10) : '-',

              PowerS1: typeof record.power1 === 'number' ? Math.round(record.power1) : '-',
              PowerS2: typeof record.power2 === 'number' ? Math.round(record.power2) : '-',
              PowerS3: typeof record.power3 === 'number' ? Math.round(record.power3) : '-',
              PowerS4: typeof record.power4 === 'number' ? Math.round(record.power4) : '-',
              PowerS5: typeof record.power5 === 'number' ? Math.round(record.power5) : '-',
              ...record,
              status
            };
          });
          tableData.value = mappedData;
          pagination.total = responsePayload.count;
          ElMessage.success(responsePayload.msg || '查询成功');
        } else {
          ElMessage.info(response?.data?.msg || '未查询到数据或响应格式不正确');
          tableData.value = [];
          pagination.total = 0;
        }


      } catch (error: any) {
        console.error('获取数据失败:', error);
        ElMessage.error(error.response?.data?.msg || error.message || '获取数据失败');
        tableData.value = [];
        pagination.total = 0;
      }
    };

    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchTableData();
    };

    const handleReset = () => {
      (Object.keys(headerSearchForm) as Array<keyof SearchForm>).forEach((key) => {
        headerSearchForm[key] = '';
      });
      handleSearch();
    };

    const handleDelete = (row: CaseDataRecord) => {
      if (!row.coilNo) {
        ElMessage.error('无法获取案例的唯一标识 (coilNo) 进行删除');
        return;
      }
      ElMessageBox.confirm(
        `确定要删除任务名称为 "${row.areaCode || row.coilNo}" 的案例吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await rollingSimulationApi.deleteCase({ volumeNum: row.coilNo! });
          // Assuming response.data contains a status or msg field for success checking
          if (response && response.data && ((response.data as any).status === 2000 || (response.data as any).msg === '删除成功' || response.status === 200)) {
            ElMessage.success((response.data as any).msg || '删除成功');
            fetchTableData();
          } else {
            ElMessage.error((response.data as any)?.msg || (response as any)?.msg || '删除失败');
          }
        } catch (error: any) {
          console.error('删除失败:', error);
          ElMessage.error(error.response?.data?.msg || error.message || '删除失败');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    };

    const handleSizeChange = (val: number) => {
      pagination.pageSize = val;
      fetchTableData();
    };

    const handleCurrentChange = (val: number) => {
      pagination.currentPage = val;
      fetchTableData();
    };

    // 行样式
    const tableRowClassName = (row: any) => {
      if (row.status === 0) return 'row-status-uncomputed';
      if (row.status === 1) return 'row-status-computed';
      if (row.status === 2) return 'row-status-computing';
      return '';
    };

    onMounted(() => {
      fetchTableData();
      window.addEventListener('resize', handleResize);
      
      // 调用 techList 和 techFit 接口
      callTechListAndTechFit();
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
    });

    const form = reactive({
      name: '',
      region: '',
      date1: '',
      date2: '',
      delivery: false,
      type: [],
      resource: '',
      desc: '',
    });
    const echartsListOptions = [
      {
        title: {
          show: true,
          text: '',
          textStyle: {
            color: '#fff'
          }
        },
        graphic: [
          {
            type: 'text',
            bottom: 45, // 距离底部的固定距离
            right: 16, // 距离底部的固定距离
            style: {
              text: '(m)', // X轴名称
              fill: '#fff',
              fontSize: 12,
              align: 'center'
            }
          }
        ],
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: { color: '#fff' },
            crossStyle: { color: '#6d7882' }
          }
        },
        grid: {
          left: '10%',
          right: '17%',
          bottom: '5%',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'slider', //滑动条
            show: true, //开启
            xAxisIndex: [0]
          }, //X轴内置滑动
          {
            type: 'inside', //内置滑动，随鼠标滚轮展示
            xAxisIndex: [0]
          }
        ],
        xAxis: [
          {
            type: 'category',
            name: '变形率(%)',
            nameLocation: 'end',     //设置name位置  start或者end

            nameTextStyle: {

              color: "#6d7882",

              fontSize: 8,

              padding: [0, 0, 0, -10] // 四个数字分别为上右下左与原位置距离

            },
            data: ['A', 'B', 'C', 'D'],
            splitLine: { show: false },

          }
        ],
        yAxis: {
          type: 'value',
          name: '屈服强度(MPa)',
          nameTextStyle: {
            fontSize: '8px',
            color: '#6d7882' // 设置 y 轴名称的颜色为红色
          },
          scale: true, //纵坐标自适应
          splitLine: {
            show: false
          }

        },
        series: [

          {
            name: '',
            data: [10, 22, 28, 43],
            type: 'line',
            stack: 'x',
            smooth: true,
            symbolSize: 1,
          }]
      }]


    return {
      headerSearchForm,
      tableData,
      pagination,
      handleSearch,
      handleReset,
      handleCheck,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      dataSourceTypeOptions,
      dataSourceType,
      dialogVisible,
      form,
      footTable,
      handleQuote,
      echartsListOptions,
      dialogPdiData,
      dialogScheduleTableData,
      dialogSimulationOutputTableData,
      tableRowClassName,
      callTechListAndTechFit,
      // expose formatters for template
      formatThicknessS1toS5,
      formatSpeedS1toS5,
      formatGapS1toS5,
      formatTensionS1toS5,
      formatRollForceS1toS5,
      formatPowerS1toS5,
      bandCellClassName,
    };
  },
});
</script>
<style scoped lang="less">
.msg-title {
  top: -4vh;
  left: 39.5vw;
  background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 2vh;
  font-weight: bolder;
  width: 10vw;
}

:deep(.el-table .cell) {
  line-height: 14px
}

::v-deep .el-table--enable-row-transition .el-table__body td {
  padding-top: 4px;
  padding-bottom: 4px;
}

/* 纵向分组底色：从“轧制力(kN)”到“功率(kW)”的一级组交替浅蓝 */
::v-deep(.band-blue) { background-color: #f3f8ff !important; }

.row-status-uncomputed {
  background: #f5f5f5 !important;
  color: #bbb !important;
}
.row-status-computing {
  background: #fffbe6 !important;
}
.row-status-computed {
  background: #f6ffed !important;
}
.btn-disabled {
  background: #e0e0e0 !important;
  color: #aaa !important;
  border-color: #e0e0e0 !important;
  cursor: not-allowed !important;
}
.dot-loading {
  display: inline-block;
  font-size: 22px;
  letter-spacing: 2px;
  animation: dotWave 1s infinite linear;
}
@keyframes dotWave {
  0% { opacity: 1; }
  33% { opacity: 0.5; }
  66% { opacity: 0.2; }
  100% { opacity: 1; }
}
</style>
